package cn.example.elasticsearch_demo.service.impl;

import cn.example.elasticsearch_demo.common.CommonPage;
import cn.example.elasticsearch_demo.dao.ESUserRepository;
import cn.example.elasticsearch_demo.entiry.ESUser;
import cn.example.elasticsearch_demo.entiry.User;
import cn.example.elasticsearch_demo.service.ESService;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class ESServiceImpl implements ESService {

    @Autowired
    public ElasticsearchOperations elasticsearchOperations;

    @Autowired
    @Qualifier("ESUserRepository")
    private ESUserRepository repository;

    @Override
    public ESUser searchById(Long id) {
        Optional<ESUser> esUser = repository.findById(id);

        return esUser.get();
    }

    @Override
    public String saveUser() {

        //1.清空索引数据
        try {
            repository.deleteAll();
        } catch (Exception e) {
            e.printStackTrace();
            e.getMessage();
        }
        //2.查询数据库数据  #这里mock
        List<User> users = new ArrayList<>();
        users.add(new User(1l, "张三", 10, "男", "北京市-朝阳区-朝阳公园-高斓大厦-88号", new Date(), new Date(), "学生"));
        users.add(new User(2l, "李四", 11, "男", "北京市-朝阳区-朝阳公园-二十一世纪大厦-88号", new Date(), new Date(), "学生"));
        users.add(new User(3l, "王五", 12, "男", "上海市-浦东区-光明路-紫光家园-22号", new Date(), new Date(), "工人"));
        users.add(new User(4l, "赵六", 13, "女", "上海市-虹桥区-机场路-国庆花园-22号", new Date(), new Date(), "工人"));
        users.add(new User(5l, "关玉玉", 11, "女", "上海市-虹桥区-机场路-国庆花园-23号", new Date(), new Date(), "老师"));
        users.add(new User(6l, "张菲菲", 12, "女", "合肥市-瑶海区-宁国路-地矿家园-23号", new Date(), new Date(), "老师"));
        users.add(new User(7l, "刘贝贝", 13, "女", "合肥市-瑶海区-宁国路-建国门-11号", new Date(), new Date(), "农民"));

        try {
            for (int i = 0; i < users.size(); i++) {
                User user = users.get(i);
                ESUser esUser = new ESUser();
                BeanUtils.copyProperties(user, esUser);
                repository.save(esUser);
            }
            return "保存成功";
        } catch (Exception e) {
            e.printStackTrace();
            return "保存失败+" + e.getMessage();
        }
    }

    @Override
    public void deleteAllUser() {
        //清空索引数据
        repository.deleteAll();
    }

    @Override
    public CommonPage<ESUser> searchUser(String keyWord, Integer pageNum, Integer pageSize) {
        try {
            PageRequest pageRequest = PageRequest.of(pageNum, pageSize);

//            NativeSearchQuery query = null;
            BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
            if (keyWord == null) {
               new NativeSearchQuery(boolQueryBuilder);
            } else {
                boolQueryBuilder.should(QueryBuilders.matchQuery("name", keyWord));
//                boolQueryBuilder.should(QueryBuilders.matchQuery("age", keyWord));
                boolQueryBuilder.should(QueryBuilders.matchQuery("sex", keyWord));
                boolQueryBuilder.should(QueryBuilders.matchQuery("address", keyWord));
//                boolQueryBuilder.should(QueryBuilders.matchQuery("caretDate", keyWord));
//                boolQueryBuilder.should(QueryBuilders.matchQuery("updateDate", keyWord));
                boolQueryBuilder.should(QueryBuilders.matchQuery("Description", keyWord));
//                query = new NativeSearchQuery(boolQueryBuilder);
            }

            NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder();

            //查询
            searchQueryBuilder.withQuery(boolQueryBuilder);
            //排序
            searchQueryBuilder.withSort(SortBuilders.fieldSort("id").order(SortOrder.ASC));//正序
            //分页
            searchQueryBuilder.withPageable(pageRequest);
            //搜索
            NativeSearchQuery build = searchQueryBuilder.build();

            SearchHits<ESUser> productHits = elasticsearchOperations.search(build, ESUser.class, IndexCoordinates.of("esuser"));

            ArrayList<ESUser> list = new ArrayList<>();
            productHits.forEach(searchHit -> {
                list.add(searchHit.getContent());
            });


            CommonPage<ESUser> commonPage = new CommonPage<>();
            commonPage.setList(list);
            commonPage.setTotal(productHits.getTotalHits());
            commonPage.setPageSize(pageRequest.getPageSize());
            commonPage.setPageNum(pageRequest.getPageNumber());

            return commonPage;
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
            return null;
        }
    }


}
